package com.hxgz.steel.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hxgz.steel.common.ServerResponse;
import com.hxgz.steel.dao.AddressMapper;
import com.hxgz.steel.domain.Address;
import com.hxgz.steel.domain.Page;
import com.hxgz.steel.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service("addressService")
public class AddressServiceImpl implements AddressService{

    @Autowired
    private AddressMapper addressMapper;


    @Override
    public ServerResponse getAddressList(Long userId, Page page){
        PageHelper.startPage(page.getCurrPageNo(),page.getPageSize());
        List<Address> addressList = addressMapper.getAddressList(userId);
        PageInfo pageInfo = new PageInfo(addressList);
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    @Transactional
    public ServerResponse addAddress(Address address){
        int count = 0;
        if(null!=address.getStatus() && address.getStatus() == 0){
            //移除默认
            int a = addressMapper.settingAddressStatus(address.getUserId());
        }else{
            address.setStatus(1);//非默认
            address.setType(1);
        }
        if(address.getId() == null){
            address.setType(1);
             count = addressMapper.insertSelective(address);
        }else{
            //设置删除
            address.setType(2);
            int countSuccess  = addressMapper.updateByPrimaryKeySelective(address);
            Address address1 = addressMapper.selectByPrimaryKey(address.getId());
            address1.setType(1);
            address1.setId(null);
            count = addressMapper.insertSelective(address1);
        }
        if(count>0){
            return ServerResponse.createBySuccessMessage("保存成功");
        }
        return ServerResponse.createByErrorMessage("保存失败");
    }

    @Override
    @Transactional
    public ServerResponse updateAddress(Long id, Long userId) {
        //设置默认
        Address address = new Address();
        address.setId(id);
        address.setStatus(0);
        int count = addressMapper.updateByPrimaryKeySelective(address);
        addressMapper.recoverStatus(userId, id);
        //设置其它为非默认
        if (count > 0) {
            return ServerResponse.createBySuccessMessage("保存成功");
        }
        return ServerResponse.createByErrorMessage("保存失败");
    }

    @Override
    @Transactional
    public ServerResponse delAddress(Long id) {
        Address address = addressMapper.selectByPrimaryKey(id);
        //设置删除
        address.setType(2);
        int count = addressMapper.updateByPrimaryKeySelective(address);
        if (count > 0) {
            return ServerResponse.createBySuccessMessage("删除成功");
        }
        return ServerResponse.createByErrorMessage("删除失败");
    }

}
